package network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:24097
 * Date:2025-10-14
 * Time:8:48
 */
public class TcpEchoServer {
    private ServerSocket sersverSocket=null;

    public TcpEchoServer(int port) throws IOException {
        sersverSocket= new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");
        ExecutorService executorService= Executors.newCachedThreadPool();
        while (true){
            //处理客户端发来的请求
            Socket clientSocket=sersverSocket.accept();
//            Thread t=new Thread(()->{
//                processConnection(clientSocket);
//            });
//            t.start();
            executorService.submit(()->{
                processConnection(clientSocket);
            });
        }
    }

    //处理客户端一个连接
    //可能要涉及到多个客户端的请求和响应
    private void processConnection(Socket clientSocket){
        System.out.printf("[%s:%d]客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()){
            //针对InputStream套了一层
            Scanner scanner=new Scanner(inputStream);
            //针对OutputStream套了一层
            PrintWriter writer=new PrintWriter(outputStream);
            while (true){
                //1.读取请求并解析
                if(!scanner.hasNext()){
                    //连接断开了
                    System.out.printf("[%s:%d]客户端下线!\n",clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                String request=scanner.next();
                //2.根据请求计算响应
                String response=process(request);
                //3.返回响应到客户端
                //outputStream.write(response.getBytes());
                writer.println(response);
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d] req: %s, resp: %s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();
    }
}
